/**
 * @create 2022-05-22
 * @desc form
 */

import type { FC } from 'react';
import { Form } from 'antd';
import cs from 'classnames';
import { CollapseFormProps, CollapseFormItemProps } from './interface';
import { FormContextProvider, useFormContext } from './form-context';

export const CollapseFormBlock: FC<{ enableCollapse: boolean }> = ({
  enableCollapse,
  children,
}) => {
  const { collapse } = useFormContext();
  const shouldCollapse = enableCollapse && collapse;

  // eslint-disable-next-line react/jsx-no-useless-fragment
  return <>{shouldCollapse ? null : children}</>;
};

export const CollapseFormItem: FC<CollapseFormItemProps> = ({
  enableCollapse,
  className,
  children,
  ...formItemProps
}) => {
  const { collapse } = useFormContext();
  const shouldCollapse = enableCollapse && collapse;
  return (
    <Form.Item {...formItemProps} className={cs({ '!hidden': shouldCollapse }, className)}>
      {children}
    </Form.Item>
  );
};

export const CollapseForm: FC<CollapseFormProps> = ({ children, collapse, ...formProps }) => {
  return (
    <FormContextProvider collapse={collapse}>
      <Form {...formProps}>{children}</Form>
    </FormContextProvider>
  );
};
